package com.school.fuyuan.business.service;

import cn.hutool.core.date.DateUtil;
import com.school.fuyuan.business.constants.InfoConstants;
import com.school.fuyuan.business.mapper.InfoManageMapper;
import com.school.fuyuan.business.mapper.UserMapper;
import com.school.fuyuan.business.model.po.InfoManage;
import com.school.fuyuan.business.model.po.User;
import com.school.fuyuan.business.model.vo.AddInfoVo;
import com.school.fuyuan.common.exception.CommonRuntimeException;
import com.school.fuyuan.common.message.RequestMsg;
import com.school.fuyuan.common.message.ResponseMsg;
import com.school.fuyuan.common.util.InfoManageUtil;
import com.school.fuyuan.common.util.ParameterUtils;
import com.school.fuyuan.common.util.TransformUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/5 22:40
 * @description
 */
@Service
public class InfoManageService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private InfoManageMapper infoManageMapper;
    @Autowired
    private UserMapper userMapper;

    private final InfoManageUtil infoManageUtil;

    public InfoManageService(InfoManageUtil infoManageUtil) {
        this.infoManageUtil = infoManageUtil;
    }


    public void addInfo(RequestMsg<AddInfoVo> addReq, ResponseMsg responseMsg) {
        boolean repeat = false;
        String userId = addReq.getHead().getUserId();
        User user = userMapper.getUser(userId);
        if (StringUtils.isEmpty(user)) {
            throw new CommonRuntimeException("998", "用户不存在");
        }
        AddInfoVo infoVo = addReq.getData();
        String num1 = infoVo.getContactNumMain();
        String num2 = infoVo.getContactNumOther();
        String parentName1 = infoVo.getParentNameMain();
        String parentName2 = infoVo.getParentNameOther();
        String studentName = infoVo.getStudentName();
        List<InfoManage> repeatInfos = infoManageMapper.getRepeatInfo(num1, num2, parentName1, parentName2, studentName, 0, 0);
        if (!CollectionUtils.isEmpty(repeatInfos)) {
            repeat = true;
        }
        InfoManage infoManage = TransformUtils.transform(infoVo, InfoManage.class);
        infoManage.setCreateUserId(userId);
        infoManage.setFollowPersonId(userId);
        infoManage.setModifyUserId(userId);
        infoManage.setEffective("1");
        infoManage.setFollowPersonName(user.getUserName());
        infoManageMapper.insertInfoManage(infoManage);
        int id = infoManage.getId();
        String appointment = infoManage.getAppointment();
        if (!ParameterUtils.isEmpty(appointment)) {
            Date appointmentDate = DateUtil.parse(appointment, "yyyy-MM-dd");
            //前一天的10点
            Date yesterdayTen = infoManageUtil.getApptDate(appointment, -1, 10, 0, 0);

            // 前天的16点
            Date yesterdaySixteen = infoManageUtil.getApptDate(appointment, -1, 16, 0, 0);

            infoManageUtil.sendApptMq(yesterdayTen, id, appointmentDate);
            infoManageUtil.sendApptMq(yesterdaySixteen, id, appointmentDate);
        }
        if (repeat) {
            List<String> userIds = repeatInfos.stream().map(InfoManage::getFollowPersonId).collect(Collectors.toList());
            List<User> users = userMapper.getUsersByUserIds(userIds);
            String msg = "本次录入数据可能有重复，请与以下人员联系:";
            for (int i = 0; i < users.size(); i++) {
                User user1 = users.get(i);
                msg += user1.getUserName() + "-" + user1.getMobile()+",";
            }
            msg = msg.substring(0, msg.lastIndexOf(","));
            msg += "。";
            responseMsg.getHead().setRespDesc(msg);
        }
    }

    public Map<String, Object> getInfoManageList(RequestMsg requestMsg) {
        String userId = requestMsg.getHead().getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new CommonRuntimeException("999", "userId不能为空");
        }
        User user = userMapper.getUser(userId);
        if (StringUtils.isEmpty(user)) {
            throw new CommonRuntimeException("998", "用户不存在");
        }
        int pageNum = requestMsg.getHead().getPageNum();
        if (pageNum < 1) {
            pageNum = 1;
        }
        int pageSize = requestMsg.getHead().getPageSize();
        if (pageSize < 0) {
            pageSize = InfoConstants.DEFAULT_PAGE_SIZE;
        }
        int pageMin = (pageNum - 1) * pageSize;
        List<InfoManage> infoManageList = infoManageMapper.getInfoManageList(userId, pageMin, pageSize);
        int counts = infoManageMapper.getInfoManageListCount(userId);
        if (ParameterUtils.isEmpty(infoManageList)) {
            infoManageList = new ArrayList<>();
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", infoManageList);
        resultMap.put("counts", counts);
        return resultMap;
    }

    public void updateInfoManage(RequestMsg<InfoManage> requestMsg) {
        String userId = requestMsg.getHead().getUserId();
        InfoManage infoManage = requestMsg.getData();
        int id = infoManage.getId();
        InfoManage infoManageData = infoManageMapper.getInfoManage(id);
        if (ParameterUtils.isEmpty(infoManageData)) {
            throw new CommonRuntimeException("-998", "修改失败，请核对信息归属人");
        }
        int result = infoManageMapper.updateInfoManage(infoManage, userId);
        if (result == 0) {
            throw new CommonRuntimeException("-997", "修改失败");
        }
    }

    public InfoManage getInfoManage(int id, String flag) {
        InfoManage infoManage = infoManageMapper.getInfoManage(id);
        if ("appt".equals(flag)) {
            infoManageMapper.updateApptStatus(id);
        }
        return infoManage;
    }

    public void changeFollow(int id, String userId, String followUserId) {
        User user = userMapper.getUser(followUserId);
        if (StringUtils.isEmpty(user)) {
            throw new CommonRuntimeException("998", "用户不存在");
        }
        InfoManage infoManageData = infoManageMapper.getInfoManage(id);
        if (ParameterUtils.isEmpty(infoManageData)) {
            throw new CommonRuntimeException("-998", "转跟进人失败，请核对信息归属人");
        }
        int result = infoManageMapper.changeFollow(id, userId, user.getUserName(), followUserId);
        if (result == 0) {
            throw new CommonRuntimeException("-997", "修改失败");
        }
    }

    public Map<String, Object> searchInfoManages(RequestMsg<Map<String, String>> requestMsg) {
        String mobile = requestMsg.getData().get("mobile");
        String name = requestMsg.getData().get("name");
        int pageNum = requestMsg.getHead().getPageNum();
        if (pageNum < 1) {
            pageNum = 1;
        }
        int pageSize = requestMsg.getHead().getPageSize();
        if (pageSize < 0) {
            pageSize = InfoConstants.DEFAULT_PAGE_SIZE;
        }
        int pageMin = (pageNum - 1) * pageSize;
        List<InfoManage> infoManageList = infoManageMapper.searchInfoManages(mobile, name, pageMin, pageSize);
        int counts = infoManageMapper.searchInfoManagesCount(mobile, name);
        if (ParameterUtils.isEmpty(infoManageList)) {
            infoManageList = new ArrayList<>();
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", infoManageList);
        resultMap.put("counts", counts);
        return resultMap;
    }

    public  Map<String, Object> getRepeatInfos(RequestMsg<Map<String, Object>> requestMsg) {
        int id = Integer.valueOf(requestMsg.getData().get("id") + "");
        int pageNum = requestMsg.getHead().getPageNum();
        if (pageNum < 1) {
            pageNum = 1;
        }
        int pageSize = requestMsg.getHead().getPageSize();
        if (pageSize < 0) {
            pageSize = InfoConstants.DEFAULT_PAGE_SIZE;
        }
        int pageMin = (pageNum - 1) * pageSize;
        InfoManage infoManage = infoManageMapper.getInfoManage(id);
        List<InfoManage> repeatInfos = infoManageMapper.getRepeatInfo(infoManage.getContactNumMain(),
                infoManage.getContactNumOther(), infoManage.getParentNameMain(),
                infoManage.getParentNameOther(), infoManage.getStudentName(),pageMin,pageSize);
        int counts = infoManageMapper.getRepeatInfoCounts(infoManage.getContactNumMain(),
                infoManage.getContactNumOther(), infoManage.getParentNameMain(),
                infoManage.getParentNameOther(), infoManage.getStudentName());
        if (ParameterUtils.isEmpty(repeatInfos)) {
            repeatInfos = new ArrayList<>();
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", repeatInfos);
        resultMap.put("counts", counts);
        return resultMap;
    }

    public void deleteInfoManges(String userId, List<Integer> infoIds) {
        User user = userMapper.getUser(userId);
        if (StringUtils.isEmpty(userId)) {
            throw new CommonRuntimeException("999", "userId不能为空");
        }
        if (StringUtils.isEmpty(user)) {
            throw new CommonRuntimeException("998", "用户不存在");
        }
        infoManageMapper.deleteInfoManges(userId, infoIds);
    }
}
